/* 运行打包 */
const { exec } = require('child_process')
const ora = require('ora')
const chalk = require('chalk')
const { succeed, error, exit } = require('../utils/index')

const buildCommand = 'vue-cli-service build' // 运行指令

/**
 * @param {String} entryMsg 选择环境时提示文字
 * @param {String} env 打包环境
 */
module.exports = async function(entryMsg, env) {
  /* 获取入口配置 */
  entries = await require('../utils/selectEntry')(entryMsg)

  const spinner = ora('打包中...')

  spinner.start()
  try {
    const buildRes = await Promise.allSettled(entries.map(item => new Promise((resolve, reject) => {
      /* 入口参数写入 */
      require('../utils/envWrite')(item)
      exec(
        `${ buildCommand } --mode ${ env }`,
        { cwd: process.cwd(), maxBuffer: 5000 * 1024 },
        (e) => {
          if (e === null) {
            resolve(`${ chalk.green(item.name) }打包完成(${ env }环境), 路径: ${ chalk.blue(item.distPath) }`)
          } else {
            reject(e.message)
          }
        }
      )
    })))

    spinner.stop()

    buildRes.forEach(res => {
      if (res.status === 'fulfilled') {
        succeed(res.value)
      } else {
        error(res.value)
      }
    })
    return {
      env,
      projects: entries.map(item => {
        return {
          ...item,
          src: `dist/${ item.entry }`
        }
      })
    }
  } catch (err) {
    error('打包失败')
    exit(err)
  }
}

